/**
 * 可以请求外部js的直接引入函数
 * @param url 请求的目标地址
 * @param options 配置一些script身上的特性
 * @see nRequireJs( url, { attr: ['async'] } )
 */
export const RequireJs = (url: string, options: any = {}) => {
  return new Promise((resolve, reject) => {
    let body: HTMLElement = document.body
    let script: HTMLScriptElement = document.createElement('script') as HTMLScriptElement
    if (typeof options.attr === 'object') {
      options.attr.forEach((item:string) => {
        script.setAttribute(item, String(true))
      })
    }
    if (typeof options.beforeCallback === 'function') {
      options.beforeCallback()
    }
    script.src = url
    script.onload = function () {
      resolve(null)
    }
    script.onerror = function () {
      reject()
    }
    body.appendChild(script)
  })
}

//请求外部Iconfont js的直接引入函数,
export const GetText = (url:string) => {
  return new Promise(function (resolve, reject) {
    let client = new XMLHttpRequest()
    client.open('GET', url)
    client.onreadystatechange = handler
    client.responseType = 'text'
    client.setRequestHeader('Accept', 'text/plan')
    client.send()

    function handler() {
      if (client.readyState !== 4) {
        return
      }
      if (client.status === 200) {
        resolve(client.response)
      } else {
        reject(new Error(client.statusText))
      }
    }
  })
}